const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');

async function testAPIs() {
  console.log('🔍 开始测试书架和借阅API...\n');

  // 创建数据库连接
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'uni_library'
  });

  try {
    // 1. 检查数据库表是否存在
    console.log('📋 检查数据库表...');
    const tables = ['books', 'bookshelf', 'borrow_records', 'cart', 'users'];
    for (const table of tables) {
      const [rows] = await connection.execute(`SHOW TABLES LIKE '${table}'`);
      if (rows.length === 0) {
        console.log(`❌ 表 ${table} 不存在`);
      } else {
        console.log(`✅ 表 ${table} 存在`);
      }
    }

    // 2. 检查是否有测试用户
    console.log('\n👤 检查测试用户...');
    const [users] = await connection.execute('SELECT id, username, phone FROM users LIMIT 5');
    if (users.length === 0) {
      console.log('❌ 没有找到用户，请先注册用户');
      return;
    }
    console.log(`✅ 找到 ${users.length} 个用户`);

    // 3. 检查是否有图书
    console.log('\n📚 检查图书...');
    const [books] = await connection.execute('SELECT id, name FROM books LIMIT 5');
    if (books.length === 0) {
      console.log('❌ 没有找到图书，请先添加图书');
      return;
    }
    console.log(`✅ 找到 ${books.length} 本图书`);

    // 4. 生成测试token
    const testUser = users[0];
    const token = jwt.sign(
      {
        userId: testUser.id,
        userType: 'student',
        isAdmin: false,
        phone: testUser.phone || '',
        username: testUser.username || 'test'
      },
      secret,
      { expiresIn: '1h' }
    );

    console.log('\n🔑 生成测试token成功');

    // 5. 测试书架添加
    console.log('\n📖 测试书架添加...');
    const testBook = books[0];
    try {
      const [existing] = await connection.execute(
        'SELECT id FROM bookshelf WHERE user_id = ? AND book_id = ?',
        [testUser.id, testBook.id]
      );

      if (existing.length > 0) {
        console.log('ℹ️  测试图书已在书架中，跳过添加测试');
      } else {
        await connection.execute(
          'INSERT INTO bookshelf (user_id, book_id) VALUES (?, ?)',
          [testUser.id, testBook.id]
        );
        console.log('✅ 书架添加测试成功');
      }
    } catch (error) {
      console.log('❌ 书架添加测试失败:', error.message);
    }

    // 6. 测试借阅
    console.log('\n📖 测试借阅...');
    try {
      // 检查图书库存
      const [bookStock] = await connection.execute(
        'SELECT stock FROM books WHERE id = ?',
        [testBook.id]
      );

      if (bookStock[0].stock <= 0) {
        console.log('ℹ️  测试图书库存不足，跳过借阅测试');
      } else {
        // 检查是否已借阅
        const [existingBorrow] = await connection.execute(
          'SELECT id FROM borrow_records WHERE user_id = ? AND book_id = ? AND status = "borrowed"',
          [testUser.id, testBook.id]
        );

        if (existingBorrow.length > 0) {
          console.log('ℹ️  已借阅测试图书，跳过借阅测试');
        } else {
          // 执行借阅
          const borrowDays = 30;
          const dueDate = new Date();
          dueDate.setDate(dueDate.getDate() + borrowDays);

          await connection.execute(
            'INSERT INTO borrow_records (user_id, book_id, borrow_date, due_date, borrow_days, status) VALUES (?, ?, NOW(), ?, ?, "borrowed")',
            [testUser.id, testBook.id, dueDate.toISOString().split('T')[0], borrowDays]
          );

          // 减少库存
          await connection.execute(
            'UPDATE books SET stock = stock - 1 WHERE id = ?',
            [testBook.id]
          );

          console.log('✅ 借阅测试成功');
        }
      }
    } catch (error) {
      console.log('❌ 借阅测试失败:', error.message);
    }

    console.log('\n🎉 API测试完成！');

  } catch (error) {
    console.error('❌ 测试过程中出错:', error);
  } finally {
    await connection.end();
  }
}

// 运行测试
testAPIs().catch(console.error);
